import requests
import logging

logger = logging.getLogger(__name__)


class API:
    def __init__(self, crawler):
        settings = crawler.settings
        self._api_url = settings.get('ST_API', 'http://localhost:8000')
        self._api_key = settings.get('ST_KEY')
        self._headers = {'Authorization': f'{self._api_key}'}
        self._sync_state = '{}/api/state'.format(self._api_url)
        self._sync_errors = '{}/api/errors'.format(self._api_url)

    def sync_state(self, state):
        response = requests.post(self._sync_state, headers=self._headers, json=state)
        logger.info(f'Send scrapy stats success, {response.text}')

    def sync_errors(self, errors):
        response = requests.post(self._sync_errors, headers=self._headers, json=errors)
        logger.info(f'Send scrapy errors success, {response.text}')
